
package gw.com.android.ui.quote2.editquote;

import android.app.Activity;
import android.graphics.Color;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.quote2.widget.ItemTouchHelperAdapter;
import gw.com.android.ui.quote2.widget.OnStartDragListener;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.TintImageView;

/**
 * 微信公众号 aikaifa 欢迎关注
 */
public class OptionalListAdapter extends RecyclerView.Adapter implements ItemTouchHelperAdapter {

    private DataItemResult mTickList;
    private LayoutInflater mInflater = null;
    public HashMap<Integer, Boolean> checkMap;
    /**
     * 上下文
     **/
    private BaseActivity mOwnerAct;
    private final OnStartDragListener mDragStartListener;

    public OptionalListAdapter(Activity mActivity, OnStartDragListener dragStartListener) {
        mOwnerAct = (BaseActivity) mActivity;
        mInflater = mActivity.getLayoutInflater();
        mDragStartListener = dragStartListener;
        checkMap = new HashMap<>();
        mTickList = new DataItemResult();
        mTickList.appendItems(DataManager.instance().getSelfTickList());
        Logger.e("mTick2 size = " + mTickList.getDataCount());
        init();
    }

    private void init() {
        if (null == mTickList || mTickList.getDataCount() <= 0) {
            return;
        }
        for (int i = 0, p = mTickList.getDataCount(); i < p; i++) {
            DataItemDetail model = mTickList.getItem(i);
            model.setBooleanValue("isSelected", false);
            checkMap.put(i, false);
        }
    }

    /**
     * 返回界面显示的选项文案
     *
     * @param position
     * @return
     */
    public DataItemDetail getItem(int position) {
        if (null != mTickList) {
            if (position >= 0 && position < mTickList.getDataCount()) {
                DataItemDetail model = mTickList.getItem(position);
                return model;
            }
        }
        return null;
    }


    /**
     * 刷新界面数据
     */
    public void refreshData() {
        mTickList.clear();
        mTickList.appendItems(DataManager.instance().getSelfTickList());
        notifyDataSetChanged();
    }

    /**
     * 保存自选数据到界面，缓存及配置中心中
     */
    public void saveSelfData() {
        DataManager.instance().addSelfTickList(mTickList);
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.optional_item_layout, parent, false);
        return new ItemViewHolder(itemView);
    }

    private boolean ifTagViewUsed = false;

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ItemViewHolder menuHolder = (ItemViewHolder) holder;
        DataItemDetail item = getItem(position);
        if (null != item) {
            String prdName = DataManager.instance().getPrdName(item);
            if (prdName != null) {
                menuHolder.itemView.setTag(item);
                menuHolder.name.setText(prdName);
                menuHolder.enName.setText(item.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
            }

            //仓位数量
            int num = DataManager.instance().getPositionNum(item.getInt(GTSConst.JSON_KEY_CODEID));
            menuHolder.tvProductState.setText(num + "");
            if (num <= 0) {//无仓位
                menuHolder.tvProductState.setVisibility(View.INVISIBLE);
            } else {
                menuHolder.tvProductState.setVisibility(View.VISIBLE);
            }
        }

        //产品信息类型，是否为参考行情
        if (item.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_REF || item.getInt(GTSConst.JSON_KEY_ZONE) == GTSConst.ZONE_TYPE_REF) {
            menuHolder.tvProductType.setText("参考");
            menuHolder.tvProductType.setSelected(true);
            menuHolder.tvProductType.setBackgroundDrawable(AppMain.getApp().getResources().getDrawable(R.drawable.common_edittext_bg_selector3));
            menuHolder.tvProductType.setTextColor(Color.parseColor("#6588F7"));
            menuHolder.tvProductType.setVisibility(View.VISIBLE);
            ifTagViewUsed = true;
        } else {
            menuHolder.tvProductType.setVisibility(View.GONE);
            ifTagViewUsed = false;
        }

        //判断是否为 推荐产品,如果是，就加上推荐标签
        if (!ifTagViewUsed)
            if (DataManager.instance().ifRecommend(item)) {
                menuHolder.tvProductType.setText("推荐");
                menuHolder.tvProductType.setSelected(true);
                menuHolder.tvProductType.setBackgroundDrawable(AppMain.getApp().getResources().getDrawable(R.drawable.common_edittext_bg_selector2));
                menuHolder.tvProductType.setTextColor(Color.parseColor("#FE6666"));
                menuHolder.tvProductType.setVisibility(View.VISIBLE);
            } else {
                menuHolder.tvProductType.setVisibility(View.GONE);
            }

//        menuHolder.checkBox.setTag(mItem);//防止划回来时选中消失
        // Start a drag whenever the handle view it touched
        menuHolder.editsort.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!NetworkMonitor.hasNetWork()) {
                    return false;
                }
                if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                    mDragStartListener.onStartDrag(menuHolder);
                }
                MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "dragsort");
                return false;
            }
        });
        menuHolder.to_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NetworkMonitor.hasNetWork()) {
                    return;
                }
                List<DataItemDetail> tickList = mTickList.getDataList();
                DataItemDetail mItem = tickList.remove(position);
                mTickList.addItem(0, mItem);
                saveSelfData();
                AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
                notifyDataSetChanged();
                MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ClickTop");
            }
        });

        if (null != item) {
            if (item.getBoolean("isSelected")) {
                menuHolder.checkBox.setImageResource(R.mipmap.a_quote_choose);
                menuHolder.checkBox.setColorValue(mOwnerAct.getResources().getColor(R.color.color_w), mOwnerAct.getResources().getColor(R.color.color_w));
            } else {
                menuHolder.checkBox.setImageResource(R.mipmap.a_quote_editunchoose);
                menuHolder.checkBox.setColorValue(mOwnerAct.getResources().getColor(R.color.color_ccccccc), mOwnerAct.getResources().getColor(R.color.color_ccccccc));
            }
            Logger.e("position:" + position + "..Checked:::" + item.getBoolean("isSelected"));
        }
    }

    private int selected(HashMap<Integer, Boolean> map) {
        int size = 0;
        for (Integer key : map.keySet()) {
            if (map.get(key)) {
                size++;
            }
        }
        return size;
    }

    public void setTickSelected(boolean selected) {
        for (int i = 0, p = mTickList.getDataCount(); i < p; i++) {
            DataItemDetail model = mTickList.getItem(i);
            model.setBooleanValue("isSelected", selected);
        }
        notifyDataSetChanged();
    }

    public int TickListSelected() {
        int size = 0;
        if (null == mTickList || mTickList.getDataCount() <= 0) {
            return size;
        }
        for (int i = 0, p = mTickList.getDataCount(); i < p; i++) {
            DataItemDetail model = getItem(i);
            if (model.getBoolean("isSelected")) {
                size++;
            }
        }
        return size;
    }

    /**
     * 删除自选
     */
    public void OnTickListRemove() {
        if (null == mTickList || mTickList.getDataCount() <= 0) {
            return;
        }
        List<DataItemDetail> tickList = mTickList.getDataList();
        Iterator iterator = tickList.iterator();
        while (iterator.hasNext()) {
            DataItemDetail itemDetail = (DataItemDetail) iterator.next();
            if (null != itemDetail && itemDetail.getBoolean("isSelected")) {
                iterator.remove();
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        if (null != mTickList) {
            return mTickList.getDataCount();
        }
        return 0;
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.checkbox)
        TintImageView checkBox;
        @BindView(R.id.product_name)
        TextView name;
        @BindView(R.id.product_sub_name)
        TextView enName;
        @BindView(R.id.product_states)
        TextView tvProductState;
        @BindView(R.id.editsort)
        ImageView editsort;
        @BindView(R.id.to_top)
        ImageView to_top;
        @BindView(R.id.product_type)
        TextView tvProductType;
        @BindView(R.id.v_divider)
        View v_divider;

        public ItemViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }

        @OnClick(R.id.checkbox)
        void OnCheckboxClick() {
            DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();
            if (mTickModel.getBoolean("isSelected")) {
                mTickModel.setBooleanValue("isSelected", false);
                mItemClickListener.onItemClick(TickListSelected());
            } else {
                mTickModel.setBooleanValue("isSelected", true);
                mItemClickListener.onItemClick(TickListSelected());
            }
            notifyDataSetChanged();
        }
    }

    public HashMap<Integer, Boolean> getMap() {
        return checkMap;
    }

    public void setMap(HashMap<Integer, Boolean> map) {
        this.checkMap = map;
        notifyDataSetChanged();
    }

    /**
     * 点击事件和长按事件
     */
    public interface ItemClickListener {
        void onItemClick(int mapSize);

        void onItemLongClick(RecyclerView.ViewHolder holder, int position);
    }

    private ItemClickListener mItemClickListener;

    public void setOnItemClickListener(ItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        Logger.e("OptionalListAdapter onItemMove form = " + fromPosition + ", to = " + toPosition);
        Collections.swap(mTickList.getDataList(), fromPosition, toPosition);
        //交换RecyclerView列表中item的位置
        notifyItemMoved(fromPosition, toPosition);
        saveSelfData();
        AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
        return true;
    }

    @Override
    public void onItemDismiss(int position) {
        Logger.e("OptionalListAdapter onItemDismiss position = " + position + ", " + mTickList.getDataCount());
        if (position >= 0 && position < mTickList.getDataCount()) {
            //删除mItems数据
            mTickList.removeByIndex(position);
            //删除RecyclerView列表对应item
            notifyItemRemoved(position);
            //删除后改变后面数据的位置
            notifyItemRangeChanged(position, mTickList.getDataCount() - position);
        }
    }

    /**
     * 根据code删除自选
     *
     * @param codeId
     */
    public void removeQuoteItem(int codeId) {
        DataItemDetail itemDetail;
        for (int i = 0; i < getItemCount(); i++) {
            itemDetail = getItem(i);
            if (null != itemDetail && itemDetail.getInt(GTSConst.JSON_KEY_CODEID) == codeId) {
                onItemDismiss(i);
                break;
            }
        }
    }

    /**
     * 添加数据
     *
     * @param model
     */
    public void addQuoteItem(DataItemDetail model) {
        model.setBooleanValue("isSelected", false);
        mTickList.addItem(model);
        notifyDataSetChanged();
    }

}
